#!/bin/bash
# Author: Ryan CHEN <chenyan@qualcomm.com>
#         Richard LIU <lrichard@qualcomm.com>
#         Jiang Wei-yin <wjiang@qualcomm.com>

LANG=en
MYNAME=$(basename $0)
VER=1.2.0

# Init database connection settings and client utility, since
# that is where choice lists of both component and feature fields
# fetched from
MYSQL=/usr/bin/mysql
DB_NAME=QRD_FeatureDepot
DB_HOST='review.qrd.qualcomm.com'
if [ ! -x $MYSQL ]; then
    echo "ERROR: there is no mysql client utility $MYSQL in this server"
    echo "Please try 'sudo apt-get install mysql-client-core-5.1' to install"
    exit 1
fi

CHECK_LICENSE="false"
HAS_LICENSE_BEFORE=
HAS_NEW_FILE=0

TAB="	"
POSTFIX=": "
MANDATORY="(*)"

Q1="Area"
Q1H="Tech domain, such as QRD_QI, QRD_BSP, QRD_AP"
Q1M="true"
GLOBAL_Q= #"hwei:ashang:yijiang:huax"
GLOBAL_G=
GLOBAL_T=
GLOBAL_DFL=chenyan
GLOBAL_S=zhangx
Q1C_AU0="QRD_QI"
	Q1C_AU0_Q="yijiang:renlongh:wjiang"
	Q1C_AU0_G=
	Q1C_AU0_T=
Q1C_AU1="QRD_BSP"
	Q1C_AU1_Q="chenyan"
	Q1C_AU1_G=
	Q1C_AU1_T=
Q1C_AU2="QRD_AP"
	Q1C_AU2_Q="yijiang:renlongh:wjiang"
	Q1C_AU2_G=
	Q1C_AU2_T=

# menu list
Q1C_MENU="$Q1 menu:
	0. $Q1C_AU0
	1. $Q1C_AU1
	2. $Q1C_AU2
"

Q2="Summary"
Q2H="The comments what change are doing such as 'Add FM speaker channel'"
Q2M="true"
Q2C_MENU=

Q3="Component Name"
Q3H="The changes will be controlled by component"
Q3M="true"

Q4="Feature Name"
Q4H="The changes will be controlled by the feature"
Q4M="true"

Q5="Fixed CRs"
Q5H="The CR fix information, It must start with 'CR' charactors such as CR123456"
Q5M="true"
Q5C_MENU=

Q6="Targets"
Q6H="Target board or chipset"
Q6M="true"

Q7="Required VUs"
Q7H="The information of VUs which the change depends on"
Q7M="false"
Q7C_MENU=

Q8="Dependency Notes"
Q8H="Another informations such as dependency change in other projects"
Q8M="false"
Q8C_MENU=

Q9="Limitations"
Q9H="The limitation of the change"
Q9M="false"
Q9C_MENU=

Q10="Suggested Testing"
Q10H="Suggested Testing for test team"
Q10M="true"
Q10C_MENU=

Q11="Peer Review"
Q11H="Who should review the change"
Q11M="false"
Q11C_MENU=

Q12="Reference Build or VU"
Q12H="Reference Build such as au-01.08.01.789-dsds-7225-dsds-w11.04"
Q12M="false"
Q12C_MENU=

Q13="Comments"
Q13H="Other comments"
Q13M="false"
Q13C_MENU=

Q100="Remote branch name"
Q100H="Please specify which remote branch you will push to"
Q100M="true"
Q100C_MENU="Remote branch menu:
"
Q14="Gerrit server"
Q14="Please specify wich gerrit server you will submit to"
Q14M="true"
Q14C_MENU="Gerrit server menu:
	1. review.qrd.qualcomm.com:29418
	2. review.qrd.qualcomm.com:39418
	3. quic-sh.ap.qualcomm.com:29418
"
Q14C_SEL="review.qrd.qualcomm.com:29418,review.qrd.qualcomm.com:39418,quic-sh.ap.qualcomm.com:29418"

# copyright define
COPYRIGHT_PREFIX="Copyright (c)"
OS_QUAL_COPYRIGHT="Code Aurora Forum."
PROP_QUAL_COPYRIGHT="QUALCOMM Incorporated."
AOSP_COPYRIGHT="The Android Open Source Project"
COPYRIGHT_SUFFIX="All Rights Reserved."
# QuIC Copyright forbitten
QUIC_COPYRIGHT="Qualcomm Innovation Center, Inc"

# license define
PROP_QUAL_LICENSE1="QUALCOMM Proprietary and Confidential."
PROP_QUAL_LICENSE2="QUALCOMM Confidential and Proprietary."
PROP_QUAL_LICENSE3="QUALCOMM Proprietary/GTDR"

APACHE_LICENSE="Licensed under the Apache License, Version 2.0 (the \"License\"); you
may not use this file except in compliance with the License.  You may
obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an \"AS IS\" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.  See the License for the specific language governing
permissions and limitations under the License.
"
APACHE_LICENSE_CHECK="Licensed under the Apache License, Version 2.0 (the \"License\"); you|may not use this file except in compliance with the License.  You may|obtain a copy of the License at||http://www.apache.org/licenses/LICENSE-2.0||Unless required by applicable law or agreed to in writing, software|distributed under the License is distributed on an \"AS IS\" BASIS,|WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or|implied.  See the License for the specific language governing|permissions and limitations under the License."

BSD_ONLY_LICENSE="Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.
    * Neither the name of Code Aurora Forum, Inc. nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"
BSD_ONLY_LICENSE_CHECK="Redistribution and use in source and binary forms, with or without|modification, are permitted provided that the following conditions are|met:|    * Redistributions of source code must retain the above copyright|      notice, this list of conditions and the following disclaimer.|    * Redistributions in binary form must reproduce the above|      copyright notice, this list of conditions and the following|      disclaimer in the documentation and/or other materials provided|      with the distribution.|    * Neither the name of Code Aurora Forum, Inc. nor the names of its|      contributors may be used to endorse or promote products derived|      from this software without specific prior written permission.||THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED|WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF|MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT|ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS|BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR|CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF|SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR|BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,|WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE|OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN|IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
GPLv2_LICENSE="This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 and
only version 2 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
"
GPLv2_LICENSE_CHECK="This program is free software; you can redistribute it and/or modify|it under the terms of the GNU General Public License version 2 and|only version 2 as published by the Free Software Foundation.||This program is distributed in the hope that it will be useful,|but WITHOUT ANY WARRANTY; without even the implied warranty of|MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the|GNU General Public License for more details."

# mailbox define
QRD_MAIL="qti.qualcomm.com"
QUIC_MAIL="quicinc.com"
CAF_MAIL="codeaurora.org"
GB_MAIL="gigabyte.com"
TS_MAIL="thunderst.com"
USER_MAIL=$(git config --get user.email | sed -e 's|.*@||g')

QUIC_MEMBER="kebina,chenyan,fsheng,renlongh,helingh,junj,yijiang,fliang,suliu,jmeng,jianfeng,bruan,sunli,nians,ywen,aiquny,zhangx,rockiec,fangpan,emmetma,figow,czhu,rayz,mwang,gnhe"

PREREVIEWER="--reviewer="
PRECC="--cc="

function banner()
{
	echo "Git Committer Tool(version "$VER")"
}

function usage()
{
	echo "Usage:"
	echo "	$MYNAME [-h | -s | messages]"
	echo
	echo "The Tool is used for QRD/IDH git committers to formalize git commit messages"
	echo
	echo "Arguments:"
	echo "	-h		Get this help information"
	echo "	-s		Special treat"
	echo "	messages	Commit messages input as following steps:"
	echo "			$Q1                   - $Q1H"
	echo "			$Q2                - $Q2H"
	echo "			$Q3         - $Q3H"
	echo "			$Q4           - $Q4H"
	echo "			$Q5              - $Q5H"
	echo "			$Q6                - $Q6H"
	echo "			$Q7           - $Q7H"
	echo "			$Q8       - $Q8H"
	echo "			$Q9            - $Q9H"
	echo "			$Q10      - $Q10H"
	echo "			$Q11            - $Q11H"
	echo "			$Q12  - $Q12H"
	echo "			$Q13               - $Q13H"
	exit 0
}

function check_author()
{
	local line

	if [ "$USER_MAIL" = "$QRD_MAIL" ]; then
		Q0A="QRD"
	fi
	if [ "$USER_MAIL" = "$QUIC_MAIL" ]; then
		Q0A="QUIC"
	fi
	if [ "$USER_MAIL" = "$CAF_MAIL" ]; then
		Q0A="CAF"
	fi
	if [ "$USER_MAIL" = "$GB_MAIL" ]; then
		Q0A="GB"
	fi
	if [ "$USER_MAIL" = "$TS_MAIL" ]; then
		Q0A="TS"
	fi

	if [ -z "$Q0A" ]; then
		echo "ERROR: Wrong git mail address"
		echo "Please use change your company mail address as committer mail address"
		echo "Change the old one by:"
		echo "	git config --add user.email <your_company_mail_address>"
		exit 1
	fi

	# for proprietary project, qualcomm mail box must be used
	git remote -v > $TMPDIR/tmp
	read line < $TMPDIR/tmp
	echo $line | grep -i "proprietary" > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		if [ "$Q0A" != "QRD" ]; then
			echo "ERROR: Wrong git mail address"
			echo "Qualcomm mailbox must be used for proprietary project"
			exit 1
		fi
	else
		# check if QuIC member use code aurora mailbox
		local quic_member
		local author
		local n
		n=1
		author=$(git config --get user.email | sed -e 's|@.*||g')
		while true; do
			quic_member=$(echo "$QUIC_MEMBER" | awk -F "," '{print $'$n'}')
			n=$(($n+1))
			if [ "$quic_member" == "" ]; then
				echo "ERROR: you are not the QuIC number!"
				exit 1
			elif [ "$quic_member" == "$author" ]; then
				if [ "$Q0A" != "CAF" ]; then
					echo "ERROR: you must use code aurora mailbox: $quic_member@codeaurora.com"
					exit 1
				fi
				break
			fi
		done
	fi
}

# parameters
#	$1 -> years string
#	$2 -> file status (A, M, ...)
#	$3 -> file name
function check_years()
{
	local current_year
	local last_year
	local last_second_year #if it has
	local line

	current_year=$(date +%Y)

	if [ "$2" == "A" ]; then
		echo "$1" | grep "^$current_year," > /dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "ERROR: Wrong copyright years for file $3"
			echo "you should write: $COPYRIGHT_PREFIX $current_year, "
			exit 1
		fi
	elif [ "$2" == "M" ]; then
		# delete the tailed charactors
		line=$(echo "$1" | sed -e 's|[, ]*$||')
		pre=$(echo "$line" | sed -e 's|[0-9][0-9]*$||')
		# get the tailed years
		if [ "$pre" == "" ]; then
			last_year=$line
		else
			last_year=$(echo "$line" | sed -e s/"$pre"//)
		fi
		if [ "$last_year" == "" ]; then
			echo "ERROR: Wrong copyright years for file $3"
			echo "you should write: $COPYRIGHT_PREFIX $current_year, "
			exit 1
		elif [ $current_year -lt $last_year ]; then
			echo "ERROR: Wrong copyright years for file $3"
			echo "the years you write is in future, check your system time using date command"
			exit 1
		elif [ $current_year -gt $(($last_year+1)) ]; then
			echo "ERROR: Wrong copyright years for file $3"
			echo "you should write: $COPYRIGHT_PREFIX $line, $current_year, "
			exit 1
		else
			if [ "$pre" == "" ]; then
				# if equal, it is assumed to be right.
				if [ $current_year -eq $(($last_year+1)) ]; then
					echo "ERROR: Wrong copyright years for file $3"
					echo "you should write: $COPYRIGHT_PREFIX $last_year-$current_year, "
					exit 1
				fi
			else
				# delete the tailed space
				line=$(echo "$pre" | sed -e 's|[ ]*$||')
				tmp=$(echo "$line" | sed -e 's|\([0-9][0-9]*\)[^0-9][^0-9]*$|\1|')
				# get the seperator before last year
				seperator1=$(echo "$line" | sed -e s/"$tmp"//)

				pre=$(echo "$tmp" | sed -e 's|[0-9][0-9]*$||')
				if [ "$pre" == "" ]; then
					last_second_year=$tmp
				else
					last_second_year=$(echo "$tmp" | sed -e s/"$pre"//)
				fi

				if [ $current_year -eq $(($last_year+1)) ]; then
					if [ "$seperator1" == "-" ]; then
						echo "ERROR: Wrong copyright years for file $3"
						echo "you should write: $COPYRIGHT_PREFIX $last_second_year-$current_year, "
						exit 1
					else
						echo "ERROR: Wrong copyright years for file $3"
						echo "you should write: $COPYRIGHT_PREFIX $last_second_year, $last_year-$current_year, "
						exit 1
					fi
				elif [ $current_year -eq $last_year ]; then
					if [ "$pre" == "" ]; then
						if [ $last_year -eq $(($last_second_year+1)) ]; then
							if [ "$seperator1" != "-" ]; then
								echo "ERROR: Wrong copyright years for file $3"
								echo "you should write: $COPYRIGHT_PREFIX $last_second_year-$current_year, "
								exit 1
							fi
						fi
					else
						line=$(echo "$pre" | sed -e 's|[ ]*$||')
						tmp=$(echo "$line" | sed -e 's|\([0-9][0-9]*\)[^0-9][^0-9]*$|\1|')
						seperator2=$(echo "$line" | sed -e s/"$tmp"//)
						if [ $last_year -eq $(($last_second_year+1)) ]; then
							if [ "$seperator2" == "-" ]; then
								echo "ERROR: Wrong copyright years for file $3"
								echo "you should write: $COPYRIGHT_PREFIX $tmp-$current_year, "
								exit 1
							elif [ "$seperator1" != "-" ]; then
								echo "ERROR: Wrong copyright years for file $3"
								echo "you should write: $COPYRIGHT_PREFIX $pre$last_second_year-$current_year, "
								exit 1
							fi
						fi
					fi

				fi
			fi
		fi
	fi
}

# Function: pre_check_copyright
# Description:
#	Black check criterion must be avoided.
#	1. CAF copyright should NOT exist in prop repository
#	2. CAF copyright should NOT exist in non-prop/bionic repository
#	3. QCOM copyright should NOT exist in non-prop repository
# parameters
#	$1 -> string line that has stripped "Copyright *** years"
#	$2 -> repository type
#	$3 -> file type
#	$4 -> file status (A, M, ...)
#	$5 -> file name
# return:
#	0 -> "All Rights Reserved." has been detected.
#	1 -> "All Rights Reserved." has not been detected.
function pre_check_copyright()
{
	local line
	line="$1"

	if [ "$2" == "proprietary" ]; then
		# CAF copyright should NOT exist in prop repository
		echo "$line" | grep "^$OS_QUAL_COPYRIGHT" > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo "ERROR: wrong copyright for file $5!!!"
			echo "you should write it like this:"
			echo "$COPYRIGHT_PREFIX $PROP_QUAL_COPYRIGHT $COPYRIGHT_SUFFIX"
			exit 1
		fi
	else
		echo "$line" | grep "^$QUIC_COPYRIGHT" > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo "ERROR: wrong copyright for file $5!!!"
			echo "QuIC copyright can not be used,"
			exit 1
		fi

		# QCOM copyright should NOT exist in non-prop repository
		echo "$line" | grep "^$PROP_QUAL_COPYRIGHT" > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo "ERROR: wrong copyright for file $5!!!"
			echo "you should write it like this:"
			echo "$COPYRIGHT_PREFIX $OS_QUAL_COPYRIGHT $COPYRIGHT_SUFFIX"
			exit 1
		fi

		# CAF copyright should NOT exist in non-prop/bionic repository
		if [ "$2" == "bionic" ]; then
			echo "$line" | grep "^$OS_QUAL_COPYRIGHT" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				echo "ERROR: you should not add any copyright for file $5"
				exit 1
			fi
			# since it does not need copyright, "All Rights Reserved" is set as detected.
			return 1
		fi
	fi

	echo "$line" | grep -i "$COPYRIGHT_SUFFIX" > /dev/null 2>&1
	return $?
}

# Function: post_check_copyright
# Description:
#	Check criterion must be fulfilled.
#	1. New added file in non-prop and non-bionic must contain CAF copyright
# parameters
#	$1 -> repository type
#	$2 -> file name
#	$3 -> file status (A, M, ...)
#	$4 -> hit if CAF copyright has been found
#	$5 -> hit if QCOM copyright has been found
function post_check_copyright()
{
	if [ "$1" != "proprietary" ]; then
		if [ "$1" != "bionic" -a "$3" == "A" ]; then
			if [ $4 -eq 0 ]; then
				echo "ERROR: wrong copyright for file $2!!!"
				echo "you should write it like this:"
				echo "$COPYRIGHT_PREFIX $OS_QUAL_COPYRIGHT $COPYRIGHT_SUFFIX"
				exit 1
			fi
		fi
	fi
	# Reserve for more check constraints here
}

# parameters
#	$1 -> line numbers in the file
#	$2 -> file name
#	$3 -> repository type
#	$4 -> file type
#	$5 -> file status (A, M, ...)
#	$6 -> AOSP copyright found
function check_license()
{
	local file_lines	# total lines in file
	local line_num		# the current line
	local line		# every line in file
	local orig_line		# every license line in template
	local license_right
	local null_counts
	local license_compared  # license template to be compared
	local license_info	# license to be printed
	local license_name

	license_right=0
	line_num=$1
	file_lines=$(awk 'END{print NR}' $2)

	if [ "$3" == "proprietary" ]; then
		line=$(awk "{if (NR==$line_num) print}" $2)
		line_num=$(($line_num+1))
		line=$(echo "$line" | sed -e 's|^[^a-zA-Z]*||')
		echo "$line" | grep "^$PROP_QUAL_LICENSE1" > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			license_right=1
		fi
		echo "$line" | grep "^$PROP_QUAL_LICENSE2" > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			license_right=1
		fi
		echo "$line" | grep "^$PROP_QUAL_LICENSE3" > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			license_right=1
		fi
		if [ $license_right -eq 1 ]; then
			return 0
		else
			echo "License Error for file $2:"
			echo "you should write like: $PROP_QUAL_LICENSE1"
			exit 1
		fi
	elif [ "$3" == "kernel" ]; then
		license_name="GPLv2"
		license_compared=$GPLv2_LICENSE_CHECK
		license_info=$GPLv2_LICENSE
	else
		if [ "$5" == "M" ]; then
			license_name="APACHE"
			license_compared=$APACHE_LICENSE_CHECK
			license_info=$APACHE_LICENSE
		elif [ "$5" == "A" ]; then
			license_name="BSD"
			license_compared=$BSD_ONLY_LICENSE_CHECK
			license_info=$BSD_ONLY_LICENSE
			if [ $6 -eq 1 ]; then
				echo "ERROR: wrong copyright for file $2:"
				echo "AOSP copyright can not be used"
				exit 1
			fi
		else
			# should never reaches here
			license_name="BSD"
			license_compared=$BSD_ONLY_LICENSE_CHECK
			license_info=$BSD_ONLY_LICENSE
			if [ $6 -eq 1 ]; then
				echo "ERROR: wrong copyright for file $2:"
				echo "AOSP copyright can not be used"
				exit 1
			fi
		fi
	fi

	# compare license line by line
	# skip some empty line
	null_counts=0;
	while [ $null_counts -le 2 ]; do
		line=$(awk "{if (NR==$line_num) print}" $2)
		line_num=$((line_num+1))
		line=$(echo "$line" | sed -e 's|^[^a-zA-Z]*||')
		if [ "$line" == "" ]; then
			null_counts=$(($null_counts+1))
		else
			break
		fi
	done
	if [ $null_counts -gt 2 ]; then
		echo "NO $license_name License found for file $2"
		echo "you should write like this:"
		echo "$license_info"
		exit 1
	fi


	local n
	n=1
	orig_line=$(echo "$license_compared" | awk -F "|" '{print $'$n'}')
	orig_line=$(echo "$orig_line" | sed -e 's|^[^a-zA-Z]*||')
	n=$(($n+1))
	# compare loop
	null_count=0
	while true; do
		if [ "$orig_line" == "" ]; then
			null_count=$(($null_count+1))
			if [ $null_count -ge 2 ]; then
				return 0
			fi
		else
			null_count=0
			echo "$line" | grep "^$orig_line" > /dev/null 2>&1
			if [ $? -ne 0 ]; then
				echo "$license_name License not match for file $2"
				echo "you should write like this:"
				echo "$license_info"
				exit 1
			fi
		fi
		orig_line=$(echo "$license_compared" | awk -F "|" '{print $'$n'}')
		n=$(($n+1))
		orig_line=$(echo "$orig_line" | sed -e 's|^[^a-zA-Z]*||')
		line=$(awk "{if (NR==$line_num) print}" $2)
		line_num=$(($line_num+1))
		line=$(echo "$line" | sed -e 's|^[^a-zA-Z]*||')
	done

	return 0
}


# parameters
#	$1 -> repository type
#	$2 -> file type
#	$3 -> file name
#	$4 -> file status (A, M, ...)
function check_copyright_license()
{
	local in_comment	# indicate if it is in comment line
	local comment_start	# indicate if "/*" appears (just for source and header code)
	local years		# years after copyright
	local line_num		# line numbers in the file
	local file_lines	# the total lines in the file
	local line
	local aosp_copyright_hits	# indicate if it has found the AOSP correct copyright
	local os_copyright_hits	# indicate if it has found the CAF correct copyright
	local prop_copyright_hits	# indicate if it has found the QCOM correct copyright

	aosp_copyright_hits=0
	os_copyright_hits=0
	prop_copyright_hits=0
	comment_start=0
	in_comment=0
	line_num=1
	file_lines=$(awk 'END{print NR}' $3)
	while [ $line_num -le $file_lines ]; do
		# read one line
		line=$(awk "{if (NR==$line_num) print}" $3)
		line_num=$(($line_num+1))
		# first delete the leading space
		line=$(echo "$line" |  sed -e 's| *\([^ ]*\)|\1|')
		# check if it is a comment line
		in_comment=0
		if [ "$2" == "source" -o "$2" == "header" ]; then
			if [ $comment_start -eq 0 ]; then
				# leading "/*" indicate that comment starts
				echo "$line" | grep "^/\*" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					comment_start=1
					in_comment=1
				fi
				# leading "//" indicate that it is a comment line
				echo "$line" | grep "^//" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					in_comment=1
				fi
			else
				in_comment=1
			fi
		elif [ "$2" == "xml" ]; then
			echo "$line" | grep '^<?' > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				continue
			fi
			if [ $comment_start -eq 0 ]; then
				# leading "<!--" indicate that comment starts
				echo "$line" | grep '^<!--' > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					comment_start=1
					in_comment=1
				fi
			else
				in_comment=1
			fi
		elif [ "$2" == "cmm" ]; then
			# leading ";" indicate that it is a comment line
			echo "$line" | grep "^;" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				in_comment=1
			fi
		else
			# leading "#" indicate that is is a comment line (including makefile, bash ...)
			echo "$line" | grep "^#" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				in_comment=1
			fi
		fi

		if [ $in_comment -eq 1 ]; then
			echo "$line" | grep -i "copyright" > /dev/null 2>&1
			# TODO :handle the copyright and license here
			if [ $? -eq 0 ]; then
				while true; do
					local res1
					local res2
					echo "$line" | grep -i "$QUIC_COPYRIGHT" > /dev/null 2>&1
					if [ $? -eq 0 ]; then
						echo "ERROR: wrong copyright!!!"
						echo "QuIC copyright can not be used for file $3"
						exit 1
					fi
					echo "$line" | grep -i "$AOSP_COPYRIGHT" > /dev/null 2>&1
					if [ $? -eq 0 ]; then
						aosp_copyright_hits=1
					fi
					echo "$line" | grep -i "$OS_QUAL_COPYRIGHT" > /dev/null 2>&1
					res1=$?
					if [ $res1 -eq 0 ]; then
						os_copyright_hits=1
					fi
					echo "$line" | grep -i "$PROP_QUAL_COPYRIGHT" > /dev/null 2>&1
					res2=$?
					if [ $res2 -eq 0 ]; then
						prop_copyright_hits=1
					fi

					if [ $res1 -eq 0 -o $res2 -eq 0 ]; then
						# strip the charactors before years
						line=$(echo "$line" | sed -e 's|.*[Cc]opyright[^0-9]*\([0-9][0-9]*.*\)|\1|')
						years=$(echo "$line" | sed -e 's|\([-0-9, ][-0-9, ]*\).*|\1|')
						check_years "$years" $4 $3
						# remove years
						line=$(echo "$line" | sed -e 's|[^a-zA-Z]*\(.*\)|\1|')
						# check copyright
						pre_check_copyright "$line" $1 $2 $4 $3
						# if it has not found "All Rights Reserved" in the same line, check in the next line
						if [ $? -ne 0 ]; then
							line=$(awk "{if (NR==$line_num) print}" $3)
							line_num=$(($line_num+1))
							echo "$line" | grep -i "$COPYRIGHT_SUFFIX" > /dev/null 2>&1
							if [ $? -ne 0 ]; then
								echo "ERROR: $COPYRIGHT_SUFFIX is missing for file $3"
								exit 1
							fi
						fi
					fi

					res1=0
					while true; do
						line=$(awk "{if (NR==$line_num) print}" $3)
						line_num=$(($line_num+1))
						# first delete the leading space
						line=$(echo "$line" | sed -e 's| *\([^ ]*\)|\1|')
						line=$(echo "$line" | sed -e 's|^[^a-zA-Z]*||')

						echo "$line" | grep -i "copyright" > /dev/null 2>&1
						if [ $? -ne 0 ]; then
							echo "$line" | grep -i "All Rights Reserved" > /dev/null 2>&1
							if [ $? -ne 0 -a "$line" != "" ]; then
								line_num=$(($line_num-1))
								res1=1
								break
							fi
						else
							break
						fi
					done
					if [ $res1 -eq 1 ]; then
						break
					fi
				done
				# Post copyright check
				post_check_copyright $1 $3 $4 $os_copyright_hits $prop_copyright_hits

				# check license
				if [ $HAS_LICENSE_BEFORE -eq 0 ]; then
					check_license $line_num $3 $1 $2 $4 $aosp_copyright_hits
				fi
				break
			fi
		else
			# if it is not a comment line and contains charactor besides space, quit the loop
			echo "$line" | grep [^ ] > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				break
			fi
		fi

		if [ "$2" == "source" -o "$2" == "header" ]; then
			echo "$line" | grep "\*/" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				comment_start=0
			fi
		elif [ "$2" == "xml" ]; then
			echo "$line" | grep '\-\->' > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				comment_start=0
			fi
		fi
	done

	# Post copyright check
	post_check_copyright $1 $3 $4 $os_copyright_hits $prop_copyright_hits
}

# parameter
#	$1 -> file name
#	$2 -> file type
# return:
#	0 -> no copyright and license
#	1 -> has copyright only
#	2 -> has license only
#	3 -> has both copyright and license
function if_has_copyright_license()
{
	local in_comment	# indicate if it is in comment line
	local comment_start	# indicate if "/*" appears (just for source and header code)
	local copyright_hits
	local license_hits
	local line
	local ret

	# just check roughly
	COPYRIGHT_KEYWORD="Copyright (C)"
	CAF_COPYRIGHT_KEYWORD="Code Aurora Forum"
	BSD_LICENSE_KEYWORD="Redistribution and use in" # for BSD, Documentation license
	LICENSE_KEYWORD1="Licensed under" # for Apache license
	LICENSE_KEYWORD2="is free software" # for GPLv2, LGPLv2.1 license
	LICENSE_KEYWORD3="SOFTWARE IS PROVIDED" # for license used by lk, also BSD hits this keyword
	LICENSE_KEYWORD4="Proprietary" # for proprietary license
	LICENSE_KEYWORD5="GPL" # for GPLv2, LGPLv2.1 license

	comment_start=0
	copyright_hits=0
	license_hits=0
	ret=0
	while read line; do
		# first delete the leading space
		line=$(echo "$line" |  sed -e 's| *\([^ ]*\)|\1|')
		in_comment=0
		if [ "$2" == "source" -o "$2" == "header" ]; then
			if [ $comment_start -eq 0 ]; then
				# leading "/*" indicate that comment starts
				echo "$line" | grep "^/\*" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					comment_start=1
					in_comment=1
				fi
				# leading "//" indicate that it is a comment line
				echo "$line" | grep "^//" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					in_comment=1
				fi
			else
				in_comment=1
			fi
		elif [ "$2" == "xml" ]; then
			echo "$line" | grep '^<?' > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				continue
			fi
			if [ $comment_start -eq 0 ]; then
				# leading "<!--" indicate that comment starts
				echo "$line" | grep '^<!--' > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					comment_start=1
					in_comment=1
				fi
			else
				in_comment=1
			fi
		elif [ "$2" == "cmm" ]; then
			# leading ";" indicate that it is a comment line
			echo "$line" | grep "^;" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				in_comment=1
			fi
		else
			# leading "#" indicate that is is a comment line (including makefile, bash ...)
			echo "$line" | grep "^#" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				in_comment=1
			fi
		fi
		if [ $in_comment -eq 1 ]; then
			echo "$line" | grep -i "$COPYRIGHT_KEYWORD" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				copyright_hits=1
				echo "$line" | grep -i "$CAF_COPYRIGHT_KEYWORD" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					has_CAF_BSD=1
				fi
			fi

			echo "$line" | grep -i -E 		\
				 "$LICENSE_KEYWORD1|$LICENSE_KEYWORD2|$LICENSE_KEYWORD3|$LICENSE_KEYWORD4|$LICENSE_KEYWORD5|$BSD_LICENSE_KEYWORD" \
				 > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				license_hits=1
				echo "$line" | grep -i "$BSD_LICENSE_KEYWORD" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					has_CAF_BSD=1
				fi
			fi
		else
			# if it is not a comment line and contains charactor besides space, quit the loop
			echo "$line" | grep "[^ ]" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				break;
			fi
		fi

		if [ "$2" == "source" -o "$2" == "header" ]; then
			echo "$line" | grep "\*/" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				comment_start=0
			fi
		elif [ "$2" == "xml" ]; then
			echo "$line" | grep '\-\->' > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				comment_start=0
			fi
		fi
	done < $1

	if [ $copyright_hits -eq 1 ]; then
		ret=$(($ret+1))
	fi
	if [ $license_hits -eq 1 ]; then
		ret=$(($ret+2))
	fi

	return $ret
}

function check_status()
{
	local STATUS
	local FOUND
	local CNT
	local URL
	local repo_type
	local file_type
	local line
	local has_CAF_BSD
	
	# get the repository name
	git remote -v > $TMPDIR/tmp
	fgrep -r "qualcomm.com/" $TMPDIR/tmp > $TMPDIR/tmp1 2> /dev/null
	sed -e 's|.*qualcomm.com/||g' $TMPDIR/tmp1 > $TMPDIR/tmp 2> /dev/null
	sed -e 's|\ (.*||g' $TMPDIR/tmp > $TMPDIR/tmp1 2> /dev/null
	sed -e 's|\.git.*||g' $TMPDIR/tmp1 > $TMPDIR/tmp 2> /dev/null

	# check the repository type such as proprietary, open source...
	read line < $TMPDIR/tmp
	line=$(echo $line | sed -e 's|new_repo\/||g')
	echo $line | grep -i "proprietary" > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		repo_type="proprietary"
	elif [ "$line" == "kernel/msm" ]; then
		repo_type="kernel"
	elif [ "$line" == "kernel/lk" ]; then
		repo_type="lk"
	elif [ "$line" == "platform/bionic" ]; then
		repo_type="bionic"
	else
		repo_type="other"
	fi

	git status -s > $TMPDIR/tmp 2> /dev/null
	if [ "$?" != "0" ]; then
		echo
		echo "ERROR: Git repository is not existing at current directory"
		echo
		exit 1
	fi
	sed -e 's| |*|g' $TMPDIR/tmp > $TMPDIR/tmp1 2> /dev/null

	# check each file to be submitted
	CNT=0
	while read line; do
		FOUND=0
		has_CAF_BSD=0
		echo "$line" > $TMPDIR/tmp 2> /dev/null
		STATUS=$(cut -c 1 $TMPDIR/tmp 2> /dev/null)

		if [ "$STATUS" = "M" ]; then
			FOUND=1
		fi
		if [ "$STATUS" = "A" ]; then
			FOUND=1
			HAS_NEW_FILE=1
		fi
		if [ "$STATUS" = "D" ]; then
			FOUND=1
		fi
		if [ "$STATUS" = "R" ]; then
			FOUND=1
		fi
		if [ "$STATUS" = "C" ]; then
			FOUND=1
		fi

		if [ $FOUND -eq 1 ]; then
			CNT=$(($CNT+1))
		if [ "$STATUS" != "M" -a "$STATUS" != "A" ]; then
			continue
		fi
		if [ "$CHECK_LICENSE" == "true" ]; then
			local extname
			# check the file type
			FILENAME=$(cut -c 4- $TMPDIR/tmp 2> /dev/null)
			echo $FILENAME | grep -i "makefile" > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				file_type="makefile"
			else
				echo $FILENAME | grep -i "kbuild" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					file_type="makefile"
				else
					# get the file extension name
					extname=$(echo $FILENAME | sed -e 's|.*\.\([^/]\)|\1|')
					if [ "$extname" == "mak" -o "$extname" == "mk" ]; then
						file_type="makefile"
					elif [ "$extname" == "c" -o "$extname" == "cpp" -o "$extname" == "java" ]; then
						file_type="source"
					elif [ "$extname" == "h" -o "$extname" == "hpp" ]; then
						file_type="header"
					elif [ "$extname" == "cmm" ]; then
						file_type="cmm"
					elif [ "$extname" == "xml" ]; then
						file_type="xml"
					else
						file_type="other"
					fi
				fi
			fi

			# we only check ascii file
			# file $FILENAME | grep ASCII > /dev/null 2> /dev/null
			file $FILENAME | grep -i text > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				local need_check
				need_check=1
				# kernel exported header files such as  include/  arch/arm/include/asm/
				# should not have copyright and license
				if [ "$repo_type" == "kernel" -a "$file_type" == "header" ]; then
					echo $FILENAME | grep -i "include" > /dev/null 2>&1
					if [ $? -eq 0 ]; then
						need_check=0
					fi
				fi
				# newly added makefile should not contain any copyright or license
				# modified makefile should not contain CAF or BSD
				if [ "$file_type" == "makefile" ]; then
					if [ "$STATUS" == "A" ]; then
						if_has_copyright_license $FILENAME $file_type
						if [ $? -gt 0 ]; then
							echo "ERROR: Should not have copyright or license for file $FILENAME"
							exit 1
						fi
					else
						if_has_copyright_license $FILENAME $file_type
						if [ $has_CAF_BSD -eq 1 ]; then
							echo "ERROR: Should not have CAF/BSD for file $FILENAME"
							exit 1
						fi
					fi
					need_check=0
				fi
				if [ "$file_type" == "other" ]; then
					if_has_copyright_license $FILENAME $file_type
					if [ $? -gt 0 ]; then
						echo "ERROR: Should not have copyright or license for file $FILENAME"
						exit 1
					fi
					need_check=0
				fi

				if [ $need_check -eq 1 ]; then
					if [ "$STATUS" != "A" ]; then
						# rebuild the original file
						cp --parent $FILENAME $TMPDIR
						git diff --cached $FILENAME | patch -d $TMPDIR -p1 -R > /dev/null 2>&1 
						# check if license exists in the original file
						if_has_copyright_license "$TMPDIR/$FILENAME" $file_type
						if [ $? -ge 2 ]; then
							HAS_LICENSE_BEFORE=1
						else
							HAS_LICENSE_BEFORE=0
						fi
					else
						HAS_LICENSE_BEFORE=0
					fi
					check_copyright_license $repo_type $file_type $FILENAME $STATUS
				fi
			else
				echo
				echo "!!! WARNING: You are committing non-ascii file: [$FILENAME] !!!"
				sleep 2
				# TODO
			fi
		fi
		fi
	done < $TMPDIR/tmp1

	if [ $CNT = 0 ]; then
		echo
		echo "ERROR: No changed files are added by 'git add'"
		echo
		exit 1
	fi
}

# parameters:
#	$1 -> mail list
#	$2 -> prefix
function compose_reviewer()
{
	local n
	local re
	n=1
	ANSWER=

	while true; do
		local reviewer
		re=$(echo $1 | awk -F ":"  '{print $'$n'}')
		if [ "$re" != "" ]; then
			ANSWER="$ANSWER $2$re@$QRD_MAIL"
			n=$(($n+1))
		else
			break
		fi
	done
}

# Function db_query
# parameters:
#   $1 -> entrance type
#   $2 -> 1st query para
#   $3 -> 2nd query para
#
function db_query()
{
	local SEL
	local MENU

	case $1 in
	"COMP")
		SQL_STMT="SELECT GROUP_CONCAT(comp_name ORDER BY comp_name) FROM components WHERE tech_area='$2'"
		;;
	"FEATURE")
		SQL_STMT="SELECT GROUP_CONCAT(t2.feature_name ORDER BY t2.feature_name) FROM components t1 \
				  JOIN feature_desc t2 ON t1.comp_id = t2.comp_ref WHERE t1.tech_area='$2' AND t1.comp_name='$3'"
		;;
	"TARGET")
		SQL_STMT="SELECT GROUP_CONCAT(target_name) FROM targets WHERE active=1"
		;;
	"REVIEWER")
		SQL_STMT="SELECT reviewer FROM components WHERE tech_area='$2' AND comp_name='$3'"
		;;
	"QUIC")
		SQL_STMT="SELECT GROUP_CONCAT(quic_alias) FROM quic_member"
		;;
	esac

	echo $SQL_STMT | $MYSQL --host=$DB_HOST --user=user             \
					--password=user --skip-column-names $DB_NAME    \
					> $TMPDIR/result.sql 2>/dev/null
	if [ $? -ne 0 ]; then
		SEL="NULL"
		echo "!!! Warning: SQL statement['$SQL_STMT'] execution failed"
		echo "Using default choice lists"
	else
		read SEL < $TMPDIR/result.sql
	fi

	cnt=1
	for i in $(echo $SEL | awk '{
		split($0, ARRAY, ",");
		for (idx=1; idx<100; idx++)
		{
			if(idx in ARRAY)
			{
				gsub(/ /,"_",ARRAY[idx]);
				printf "%s ",ARRAY[idx];
			}
		}
	}'); do
		MENU="$MENU        $cnt. $i
"
		cnt=$(($cnt+1))
	done

	case $1 in
	"COMP")
		Q3C_MENU="Please select component name:
"
		if [ "$SEL" = "NULL" ]; then
			Q3C_SEL="None"
			Q3C_MENU="$Q3C_MENU        1. None"
		else
			Q3C_SEL=$SEL
			Q3C_MENU=$Q3C_MENU$MENU
		fi
		;;
	"FEATURE")
		Q4C_MENU="Please select feature name:
"
		if [ "$SEL" = "NULL" ]; then
			Q4C_SEL="None"
			Q4C_MENU="$Q4C_MENU        1. None"
		else
			Q4C_SEL=$SEL
			Q4C_MENU=$Q4C_MENU$MENU
		fi
		;;
	"TARGET")
		Q6C_MENU="Please select target:
"
		if [ "$SEL" = "NULL" ]; then
			Q6C_SEL="msm7625_sku1,msm7625_sku3,msm7627_sku1,msm7627_sku2,msm7627A_sku1,msm7627A_sku2,msm7627A_sku3,msm7627A_sku4,ALL"
			Q6C_MENU="$Q6C_MENU        1. msm7625_sku1
	2. msm7625_sku3
	3. msm7627_sku1
	4. msm7627_sku2
	5. msm7627A_sku1
	6. msm7627A_sku2
	7. msm7627A_sku3
	8. msm7627A_sku4
	9. ALL
"
		else
			Q6C_SEL=$SEL
			Q6C_MENU=$Q6C_MENU$MENU
		fi
		;;
	"REVIEWER")
		if [ "$SEL" != "NULL" ]; then
			Q1E=$SEL
		fi
		;;
	"QUIC")
		if [ "$SEL" != "NULL" ]; then
			QUIC_MEMBER=$SEL
		fi
		;;
	esac
}

# Function msg_input
# parameters:
#	$1 -> question message
#	$2 -> help message
#	$3 -> mandatory
#	$4 -> menu
#	$5 -> message input by command line
function msg_input()
{
	if [ -n "$4" ]; then
		echo "$4"
	fi

	if [ "$3" = "true" ]; then
		while true; do
			echo -n "$TAB""$1""$MANDATORY""$POSTFIX"
			if [ -z "$5" ]; then
				read ANSWER
				if [ -z "$ANSWER" ]; then
					echo
					echo "ERROR: You MUST fill the [$1]"
					echo "[$1]: $2"
				else
					break
				fi
			else
				echo "$5"
				ANSWER="$5"
				break
			fi
		done
	else
		echo -n "$TAB""$1""$POSTFIX"
		if [ -z "$5" ]; then
			read ANSWER
		else
			echo "$5"
			ANSWER="$5"
		fi
	fi
}

# Function make_selection
# pararmters:
#	$1 -> strings seperated by ","
function make_selection()
{
	local idx
	local iter
	local sel
	local sel_nums
	local length
	local delimits

	idx=0
	delimits=", : ;"
	sel_nums="$ANSWER"
	length=${#sel_nums}
	ANSWER=""

	while true; do
		sel=""
		iter=${sel_nums:$idx:1}

		# consume redundant blank characters
		while [ "${delimits[@]/$iter/}" != "${delimits[@]}" ]; do
			idx=$(($idx+1))
			iter=${sel_nums:$idx:1}
		done

		if [ $idx -ge $length ]; then
			break
		fi

		# pick up a word
		while [ -n "$iter" -a "${delimits[@]/$iter/}" = "${delimits[@]}" ]; do
			sel=$sel$iter
			idx=$(($idx+1))
			iter=${sel_nums:$idx:1}
		done

		echo $sel | grep -E '[^0-9]' > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo "ERROR: Please enter choice number instead of manual input!"
			exit 1
		else
			ANSWER="$ANSWER,$(echo "$1" | awk -F ","  '{print $'$sel'}')"
		fi

		idx=$(($idx+1))
	done

	# truncate the first comma
	if [ "$ANSWER" != "" ]; then
		ANSWER=${ANSWER:1}
	fi
}

# Function get_CR_details
# paramters:
#	$1 -> CR lists seperated by comma
function get_CR_details()
{
	local CR_name
	local index
	local details

	index=1
	CR_DETAILS=""
	while true; do
		CR_name=$(echo "$1" | awk -F "," '{printf $'$index'}')
		if [ "$CR_name" == "" ]; then
			break
		fi
		index=$(($index+1))
		CR_name=$(tr '[a-z]' '[A-Z]' <<<"$CR_name")
		local prefix
		prefix=${CR_name:0:2}
		if [ "$prefix" == "CR" ]; then
			details=""
			while [ -z "$details" ]; do
				echo -ne "\t$CR_name$MANDATORY$POSTFIX"
				read details
			done
			CR_DETAILS+="
		$CR_name$POSTFIX$details"
		fi
	done
}

# Function commit
# parameters:
#	$1 -> Area
#	$2 -> Summary
#	$3 -> Components
#	$4 -> Features
#	$5 -> Fixes
#	$6 -> Targets
#	$7 -> Reference Build(s)
#	$8 -> Required VUs
#	$9 -> Dependency Notes
#	$10 -> Limitations
#	$11 -> Suggested Testing
#	$12 -> Peer Review
#	$13 -> Comments
function commit()
{
	local ST
	local ANSWER
	local AREA
	ST="false"

	banner

	if [ "$1" = "-h" ]; then
		usage
	else
		echo "use '$MYNAME -h' to get help"
	fi

	if [ "$1" = "-s" ]; then
		ST="true"
	fi

	db_query "QUIC" "" ""
	check_author

	if [ "$ST" != "true" ]; then
		check_status
	fi

	echo
	echo "Please enter your commit comments one by one"
	echo "Note: (*) item(s) MUST be filled"
	echo

	msg_input "$Q1" "$Q1H" "$Q1M" "$Q1C_MENU" "$1"
	if [ -n "$Q1C_MENU" ]; then
		while [ -z "$Q1A" ]; do
			case $ANSWER in
			"0")
				Q1A="$Q1C_AU0"
				Q1E="$Q1C_AU0_Q"
				AREA="$Q1C_AU0"
				;;
			"$Q1C_AU0")
				Q1A="$Q1C_AU0"
				Q1E="$Q1C_AU0_Q"
				AREA="$Q1C_AU0"
				;;
			"1")
				Q1A="$Q1C_AU1"
				Q1E="$Q1C_AU1_Q"
				AREA="$Q1C_AU1"
				;;
			"$Q1C_AU1")
				Q1A="$Q1C_AU1"
				Q1E="$Q1C_AU1_Q"
				AREA="$Q1C_AU1"
				;;
			"2")
				Q1A="$Q1C_AU2"
				Q1E="$Q1C_AU2_Q"
				AREA="$Q1C_AU2"
				;;
			"$Q1C_AU2")
				Q1A="$Q1C_AU2"
				Q1E="$Q1C_AU2_Q"
				AREA="$Q1C_AU2"
				;;
			*)
				echo "!!! Warning: You specify one new item for [$Q1] !!!"
				Q1A="$ANSWER"
				Q1E="$GLOBAL_DFL"
				AREA=""
				;;
			esac
		done
	fi

	msg_input "$Q2" "$Q2H" "$Q2M" "$Q2C_MENU" "$2"
	Q2A="$ANSWER"

	db_query "COMP" "$AREA" ""
	msg_input "$Q3" "$Q3H" "$Q3M" "$Q3C_MENU" "$3"
	make_selection "$Q3C_SEL"
	Q3A="$ANSWER"

	db_query "REVIEWER" "$AREA" "$Q3A"
	db_query "FEATURE" "$AREA" "$Q3A"
	msg_input "$Q4" "$Q4H" "$Q4M" "$Q4C_MENU" "$4"
	make_selection "$Q4C_SEL"
	Q4A="$ANSWER"

	msg_input "$Q5" "$Q5H" "$Q5M" "$Q5C_MENU" "$5"
	Q5A="$ANSWER"
	CR_DETAILS=""
	get_CR_details "$ANSWER"

	db_query "TARGET" "" ""
	msg_input "$Q6" "$Q6H" "$Q6M" "$Q6C_MENU" "$6"
	make_selection "$Q6C_SEL"
	Q6A="$ANSWER"

	msg_input "$Q7" "$Q7H" "$Q7M" "$Q7C_MENU" "$7"
	Q7A="$ANSWER"

	msg_input "$Q8" "$Q8H" "$Q8M" "$Q8C_MENU" "$8"
	Q8A="$ANSWER"

	msg_input "$Q9" "$Q9H" "$Q9M" "$Q9C_MENU" "$9"
	Q9A="$ANSWER"

	msg_input "$Q10" "$Q10H" "$Q10M" "$Q10C_MENU" "${10}"
	Q10A="$ANSWER"

	msg_input "$Q11" "$Q11H" "$Q11M" "$Q11C_MENU" "${11}"
	Q11A="$ANSWER"

	msg_input "$Q12" "$Q12H" "$Q12M" "$Q12C_MENU" "${12}"
	Q12A="$ANSWER"

	msg_input "$Q13" "$Q13H" "$Q13M" "$Q13C_MENU" "${13}"
	Q13A="$ANSWER"

	# commit it
	echo
	git commit -m "$Q0A:$Q1A:$Q3A:$Q4A:$Q5A:$Q2A

	$Q3$POSTFIX$Q3A
	$Q4$POSTFIX$Q4A
	$Q5$POSTFIX$Q5A$CR_DETAILS
	$Q6$POSTFIX$Q6A
	$Q7$POSTFIX$Q7A
	$Q8$POSTFIX$Q8A
	$Q9$POSTFIX$Q9A
	$Q10$POSTFIX$Q10A
	$Q11$POSTFIX$Q11A
	$Q12$POSTFIX$Q12A
	$Q13$POSTFIX$Q13A
	(*commit tool - $VER)
"
	if [ "$?" != "0" ]; then
		echo
		echo "ERROR: Commit failed!"
		echo
		exit 1
	fi

	if [ $HAS_NEW_FILE -eq 1 ]; then
		Q1E="$Q1E:$GLOBAL_S"
	fi
	compose_reviewer "$Q1E" "$PREREVIEWER"
	REVIEWER="$ANSWER"
	compose_reviewer "$GLOBAL_Q" "$PRECC"
	CC="$ANSWER"

	# Remote branch menu
	git branch -r > $TMPDIR/tmp 2> /dev/null
	cut -c 3- $TMPDIR/tmp > $TMPDIR/tmp1 2> /dev/null
	sed -e 's|.*/||g' $TMPDIR/tmp1 > $TMPDIR/remote_branches 2> /dev/null

	local n
	n=1
	RB=
	while read line; do
		Q100C_MENU="$Q100C_MENU$TAB""$n"". ""$line
"
		if [ "$Q100C_SEL" == "" ]; then
			Q100C_SEL="$line"
		else
			Q100C_SEL="$Q100C_SEL,$line"
		fi
		n=$((n+1))
	done < $TMPDIR/remote_branches

	msg_input "$Q100" "$Q100H" "$Q100M" "$Q100C_MENU"
	make_selection "$Q100C_SEL"
	Q100A="$ANSWER"


	git remote -v > $TMPDIR/tmp
	fgrep -r "qualcomm.com/" $TMPDIR/tmp > $TMPDIR/tmp1 2> /dev/null
	sed -e 's|.*qualcomm.com/||g' $TMPDIR/tmp1 > $TMPDIR/tmp 2> /dev/null
	sed -e 's|\ (.*||g' $TMPDIR/tmp > $TMPDIR/tmp1 2> /dev/null
	sed -e 's|\.git.*||g' $TMPDIR/tmp1 > $TMPDIR/tmp 2> /dev/null
	read line < $TMPDIR/tmp
	if [ "$line" = "" ]; then
		echo
		echo "You are creating new project or it's not QRD project"
		while true; do
			echo -n "PLease enter project name:"
			read ANSWER
			if [ -z "$ANSWER" ]; then
				echo
				echo "ERROR: You MUST fill the [project name]"
			else
				PRJ=$ANSWER
				break
			fi
		done
	else
		PRJ=$line
	fi

	msg_input "$Q14" "$Q14H" "$Q14M" "$Q14C_MENU" "${14}"
	make_selection "$Q14C_SEL"
	Q14A="$ANSWER"

	# XXX: remove new_repo strings
	PRJ=$(echo $PRJ | sed -e 's|new_repo\/||g')
	# push it
	nServ=1
	nRB=1
	USER_NAME=$(git config --get user.name)
	echo "$USER_NAME" | grep -E '^[a-zA-Z]*$' > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo "ERROR: (git config --global user.name) is invalid!"
		echo "Please modify user.name in ~/.gitconfig to keep the same with Gerrit Username"
		exit 1
	fi

	while true; do
		G_SERVER=$(echo "$Q14A" | awk -F ","  '{print $'$nServ'}')
		RB=$(echo "$Q100A" | awk -F ","  '{print $'$nRB'}')
		if [ "$G_SERVER" == "" ]; then
			break
		fi
		if [ "$RB" == "" ]; then
			nRB=1
			nServ=$(($nServ+1))
			continue
		fi
		nRB=$(($nRB+1))

#git push --receive-pack="git receive-pack $REVIEWER $CC" ssh://$USER_NAME@$G_SERVER/$PRJ.git HEAD:refs/for/$RB 2>&1 | tee $TMPDIR/tmp
#		if [ "$?" != "0" ]; then
#			echo
#			echo "ERROR: Push failed!"
#			echo
#			exit 1
#		fi

		# set review bit to -1, if new file detected
		if [ $HAS_NEW_FILE -eq 1 ]; then
			local cid
			local pid
			local host
			local port

			pid=1
			while read line; do
				echo "$line" | grep -E "^remote:.*:[0-9][0-9]*/[0-9][0-9]*" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					cid=$(echo "$line" | sed -e 's|^remote:.*:[0-9][0-9]*/\([0-9][0-9]*\).*$|\1|')
					break
				fi
			done < $TMPDIR/tmp
			if [ "$cid" == "" ]; then
				echo "ERROR: Can't find Gerrit change-ID"
				echo
				exit 1
			fi

			host=$(echo "$G_SERVER" | sed -e 's|\(.*\):[0-9][0-9]*|\1|')
			port=$(echo "$G_SERVER" | sed -e 's|.*:\([0-9][0-9]*\)|\1|')
			ssh -p $port $USER_NAME@$host gerrit review --code-review -1 --message '"Set review bit to -1 for new file scan"' $cid,$pid
			if [ $? -ne 0 ]; then
				echo "ERROR: Set gerrit review bit failed!"
				echo
				exit 1
			fi
		fi
	done
}

function mak_tmp_dir()
{
	local tmp_dir
	local logname
	# environment variables that can be accepted by linux, see:
	# http://en.wikipedia.org/wiki/TMPDIR
	if [ -n "$TMPDIR" ]; then
		tmp_dir="$TMPDIR"
	elif [ -n "$TEMP" ]; then
		tmp_dir="$TEMP"
	elif [ -n "$TEMPDIR" ]; then
		tmp_dir="$TEMPDIR"
	elif [ -n "$TMP" ]; then
		tmp_dir="$TMP"
	else
		tmp_dir="/tmp"
	fi

	logname=$(whoami)
	TMPDIR="$tmp_dir/$logname/$MYNAME"

	rm -rf $TMPDIR
	mkdir -p $TMPDIR

	if [ $? -ne 0 ]; then
		echo "temporary directory can not be accessed: $tmp_dir"
		exit 1
	fi
}

mak_tmp_dir
commit $@

